package grade;

import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;

public class Tool {
	private static String driver;
	private static String url;
	private static String useName;
	private static String passWord;

	static {
		Properties pro = new Properties();
		InputStream is = null;
		try {
			is = Tool.class.getClassLoader().getResourceAsStream(
					"config.properties");
			pro.load(is);
		} catch (Exception e) {
			e.printStackTrace();
		}
		driver = pro.getProperty("driver");
		url = pro.getProperty("url");
		useName = pro.getProperty("useName");
		passWord = pro.getProperty("passWord");
	}

	public static Connection open() {
		try {
			Class.forName(driver);
			return DriverManager.getConnection(url, useName, passWord);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	public static void close(Statement st, Connection con, ResultSet rs) {
		close(st);
		close(con);
		close(rs);
	}

	public static void close(Statement st) {
		if (st != null) {
			try {
				st.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
	}

	public static void close(Connection con) {
		if (con != null) {
			try {
				con.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
	}

	public static void close(ResultSet rs) {
		if (rs != null) {
			try {
				rs.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
	}

	public int executeUpdate(String sql, Object... args) {
		Connection con = open();
		PreparedStatement ps = null;
		try {
			ps = con.prepareStatement(sql);
			for (int i = 0; i < args.length; i++) {
				ps.setObject(i + 1, args[i]);
			}
			return ps.executeUpdate();
		} catch (SQLException e) {
			e.printStackTrace();
			throw new RuntimeException(e);
		} finally {
			close(null, con, null);
		}
	}

	public int executeUpdate1(String sql, Object... args) {
		Connection con = open();
		PreparedStatement ps = null;
		ResultSet rs = null;
		int k = 0;
		try {
			ps = con.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS);
			for (int i = 0; i < args.length; i++) {
				ps.setObject(i + 1, args[i]);
			}
			ps.executeUpdate();
			rs = ps.getGeneratedKeys();
			if (rs.next())
				k = rs.getInt(1);
			return k;
		} catch (SQLException e) {
			e.printStackTrace();
			throw new RuntimeException(e);
		} finally {
			close(null, con, null);
		}
	}

}